import 'dart:ui';

import 'package:airbnb_clone/components/dialog/login_check_dialog.dart';
import 'package:airbnb_clone/components/dialog/msg_dialog.dart';
import 'package:airbnb_clone/internal/http/dao/article_create_dao.dart';
import 'package:airbnb_clone/internal/login_check/login_check.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

import '../../../constant/constant.dart';
import '../../../models/response.dart';

class AddScreen extends StatefulWidget {
  const AddScreen({super.key});

  @override
  State<AddScreen> createState() => _AddScreenState();
}

class _AddScreenState extends State<AddScreen> {
  String _title = "";
  String _articleContext = "";
  // final _titleController = TextEditingController();
  // final _articleContextController = TextEditingController();
  final GlobalKey _formKey = GlobalKey<FormState>();
  bool _isLogin = true;
  @override
  void initState() {
    super.initState();
    if (!LoginCheck.check()) {
      _isLogin = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        body: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: bgGradientColor,
              ),
            ),
            child: !_isLogin
                ? needLoginWidget(context)
                : Form(
                    key: _formKey,
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    child: ListView(
                      padding: const EdgeInsets.symmetric(horizontal: 20),
                      children: [
                        buildTopBar(),
                        // shadowWidget(buildChooseBelong()),
                        shadowWidget(buildTitleTextField()),
                        shadowWidget(buildArticleContextTextField()),
                        // shadowWidget(buildArticleImgField()),
                        shadowWidget(buildConfirmButton(context))
                      ],
                    ))),
      ),
    );
  }

  Widget buildConfirmButton(BuildContext context) {
    return TextButton(
      style:
          ButtonStyle(overlayColor: MaterialStateProperty.resolveWith((states) {
        return const Color.fromARGB(0, 124, 120, 120);
      })),
      child: const Text(
        "创建",
        style: TextStyle(
            color: Colors.black, fontSize: 24, fontWeight: FontWeight.w600),
      ),
      onPressed: () async {
        FocusScope.of(context).unfocus();
        if ((_formKey.currentState as FormState).validate()) {
          (_formKey.currentState as FormState).save();
          create();
        }
      },
    );
  }

  Future<void> create() async {
    if (!LoginCheck.check()) {
      LoginCheckDialog.loginDialog(context);
      return;
    }
    TiebaResponse response =
        await ArticleCreateDao.create(_title, _articleContext);
    if (response.code == 200) {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    }
  }

  Container shadowWidget(Widget widget) {
    return Container(
      margin: const EdgeInsets.only(bottom: 14),
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 8,
                offset: const Offset(3, 3))
          ]),
      child: widget,
    );
  }

// 顶部导航栏
  Widget buildTopBar() {
    return Container(
      margin: const EdgeInsets.all(10),
      decoration:
          BoxDecoration(gradient: LinearGradient(colors: topBarBgColor)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          IconButton(
              onPressed: () {
                // Navigator.pop(context);
              },
              icon: const Icon(
                Icons.arrow_back_ios_new,
                color: Colors.transparent,
              )),
          const Text(
            "发布文章",
            style: TextStyle(fontWeight: FontWeight.w800, fontSize: 20),
          ),
          IconButton(
              onPressed: () {
                // if (_fromkey.currentState!.validate()) {
                //   _uploadArticle();
                // }
              },
              icon: const Icon(
                Icons.send_outlined,
                color: Colors.transparent,
              ))
        ],
      ),
    );
  }

// 发布吧选择
  Widget buildChooseBelong() {
    return const ListTile(
      leading: Icon(Icons.content_paste_search_sharp),
      title: Text("选择吧"),
    );
  }

// 标题输入
  Widget buildTitleTextField() {
    return TextFormField(
      // controller: _titleController,
      decoration: const InputDecoration(
          labelText: '标题',
          labelStyle: TextStyle(fontWeight: FontWeight.w800, fontSize: 20),
          border: InputBorder.none),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '标题不能为空';
        }
        return null;
      },
      onSaved: (v) => _title = v!,
    );
  }

// 内容输入
  Widget buildArticleContextTextField() {
    FocusNode focusNode = FocusNode();
    return TextFormField(
      focusNode: focusNode,
      onEditingComplete: () {
        // _focusNode.
      },
      // controller: _articleContextController,
      maxLines: 10,
      decoration: const InputDecoration(
          labelText: '内容',
          labelStyle: TextStyle(fontWeight: FontWeight.w800, fontSize: 20),
          border: InputBorder.none),
      validator: (value) {
        if (value == null || value.isEmpty) {
          // FocusScope.of(context).requestFocus(focusNode);
          return '内容不能为空';
        }
        return null;
      },
      onSaved: (v) => _articleContext = v!,
    );
  }

// 上传图片列表
  Widget buildArticleImgField() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        buildUploadImg(),
        buildUploadImg(),
        buildUploadImg(),
      ],
    );
  }

// 上传组件
  Widget buildUploadImg() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(4),
      child: Container(
        margin: const EdgeInsets.fromLTRB(5, 30, 5, 0),
        width: 100,
        height: 100,
        color: const Color.fromARGB(30, 0, 0, 0),
        child: Center(
          child: IconButton(onPressed: () {}, icon: const Icon(Icons.add)),
        ),
      ),
    );
  }

  Widget needLoginWidget(BuildContext context) {
    return GestureDetector(
      child: Center(
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
          child: Container(
            height: 195,
            width: 300,
            padding: const EdgeInsets.fromLTRB(20, 10, 20, 10),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(20)),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "用户未登录",
                  style: titleTextStyle,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    TextButton(
                      onPressed: () {
                        context.pushNamed("login");
                      },
                      style: normalButtonStyle,
                      child: Text(
                        "点击登录",
                        style: normalTextStyle,
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
